package com.supermarket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supermarket.entity.Provider;
import com.supermarket.mapper.ProviderMapper;
import com.supermarket.service.ProviderService;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class ProviderServiceImpl extends ServiceImpl<ProviderMapper, Provider> implements ProviderService {
    
    @Autowired
    private ProviderMapper providerMapper;
    
    @Override
    public Provider getById(Long id) {
        return providerMapper.selectById(id);
    }

    @Override
    public List<Provider> getAll() {
        return providerMapper.selectAll();
    }

    @Override
    public void create(Provider provider) {
        provider.setCreatedBy(1L);
        provider.setCreationDate(new Date(TimeZone.getTimeZone("UTC").getOffset(System.currentTimeMillis()) + System.currentTimeMillis()));
        providerMapper.insert(provider);
    }

    @Override
    public void update(Provider provider) {
        providerMapper.update(provider);
    }

    @Override
    public void delete(Long id) {
        providerMapper.deleteById(id);
    }
    
    @Override
    public R<Object> getProviderList(Integer currentPage, Integer pageSize, String proCode, String proName) {
        try {
            // 计算分页参数
            int start = (currentPage - 1) * pageSize;
            
            // 获取供应商列表
            List<Provider> providerList = providerMapper.getProviderList(start, pageSize, proCode, proName);
            
            // 获取总记录数
            int totalCount = providerMapper.getProviderCount(proCode, proName);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("list", providerList);
            data.put("currentPage", currentPage);
            data.put("pageSize", pageSize);
            data.put("totalCount", totalCount);
            
            return R.createSuccess(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "查询失败：" + e.getMessage());
        }
    }
}
